package com.js.common.core;

import cn.hutool.core.util.ReUtil;
import com.js.common.annotation.ResponseCommand;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import net.mamoe.mirai.event.events.FriendMessageEvent;
import net.mamoe.mirai.event.events.GroupMessageEvent;
import net.mamoe.mirai.event.events.MessageEvent;
import net.mamoe.mirai.message.data.Image;
import net.mamoe.mirai.message.data.MessageChain;
import net.mamoe.mirai.message.data.MessageChainBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Data
@Slf4j
@Scope("prototype")
public class BotHandler extends BotSend {

    @Value("${bot.master}")
    private long master;
    /**
     * 消息事件
     */
    private MessageEvent event;
    /**
     * 群聊
     */
    private GroupMessageEvent group;
    /**
     * 私聊
     */
    private FriendMessageEvent friend;
    /**
     * 内容
     */
    private List<String> content;

    @Async("wsExecutor")
    public void handler(long userId, long targetId, MessageChain messageChain) throws InvocationTargetException, IllegalAccessException {
        Method[] methods = this.getClass().getMethods();
        //设置缓存key
        setCacheKeyPrefix(userId + "#" + targetId + "#" + this.getClass().getName() + "#");
        for (Method method : methods) {
            //内置指令注解
            ResponseCommand responseCommand = method.getAnnotation(ResponseCommand.class);
            MessageChain result = null;
            if(responseCommand == null){
                //没有指令注解的方法进入缓存判断是否前置指令的后续方法
                if(!isSkip() && containCache(method.getName())){
                    result = (MessageChain) method.invoke(this, userId, targetId, "", messageChain);
                }
            }else{
                //管理员指令判断
                if(responseCommand.master() && getMaster() != userId){
                    return;
                }
                boolean valid = ReUtil.isMatch(responseCommand.value(), messageChain.contentToString().trim());
                if(valid){
                    String[] reg = responseCommand.reg();
                    if(reg.length > 0){
                        setContent(new ArrayList<>());
                        for (int i = 0; i < reg.length; i++) {
                            Pattern pattern = Pattern.compile(reg[i]);
                            getContent().add(ReUtil.replaceFirst(pattern, messageChain.contentToString().trim(), ""));
                        }
                    }
                    //执行指令方法
                    try {
                        result = (MessageChain) method.invoke(this, userId, targetId, responseCommand.value(), messageChain);
                    }catch (Exception e){
                        log.error("处理出现异常", e);
                        MessageChainBuilder builder = new MessageChainBuilder();
                        result = builder.append("处理出现异常").build();
                    }
                }
            }
            //有返回值就发送消息
            if(result != null){
                send(userId, targetId, result);
            }
        }
    }

    public Image uploadImage(String template, Map<String, Object> map){
        return null;
    }
}